<?php 
namespace app\model;

use think\model;
use think\facade\Db;
use think\facade\Cache;

class DeptModel extends Model 
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'dept';
    // 设置当前模型的数据库连接
    //protected $connection = 'db_config';
    //protected $pk = 'id';

    protected $dept_temp=[];

    // 模型初始化
    protected static function init()
    {
        
    }

    public function getAll($noCache=0){
        $list = Cache::get('dept');
        if($noCache==1) $list='';
        
        if(!$list){
            $list=[];
            $depts = Db::table("dept")->select()->toArray();
            foreach($depts as $k=>$v){
                $list[$v['id']]=$v;
            }
            Cache::set('dept',$list,300);
        }
        return $list;
    }



    //初始化部门树
    public function deptTree($id=1){

        //建立一个部门数组
        if(!$this->dept_temp){
            $list = Db::table('dept')->order('id')->select();
            $this->dept_temp = $list;
        }
    
        $dept=[];
        foreach($this->dept_temp as $d){
            if($d['id']==$id){
                $dept[]= $d;
                break;
            }
        }

        $this->getSubDept($id,$dept,1);

        return ($dept);
    }


    //递归取得子部门
    public function getSubDept($id,&$arr=[],$deep=0){
         foreach($this->dept_temp as $d){
            if($d['fid']==$id){
                $d['imgs']+=$deep;
                $arr[] = $d;
                $this->getSubDept($d['id'],$arr,$deep+1);
            }
        }
        return $arr;
    }    

}

